[CmdletBinding()]
param (
    [Parameter()]
    [switch]
    $Beta
)

$GIT_TAG = git describe --tags
$IMAGE_NAME = "quick-certs"
$IMAGE_TAG = $GIT_TAG

$IMAGE_NAME_AND_TAG_LATEST = "$($IMAGE_NAME):latest"

if ($Beta) {
    $IMAGE_TAG += "-beta"
}

$CurrentImages = docker images
$CurrentImages = $CurrentImages[1..($CurrentImages.Length - 1)]
$CurrentImages = $CurrentImages 
| ForEach-Object { 
    $parts = $([System.Text.RegularExpressions.Regex]::Split($_, "[\s]+"))
    $obj = [PSCustomObject]@{
        REPOSITORY = $parts[0]
        TAG        = $parts[1]
        IMAGEID    = $parts[2]
    }
    Write-Output @obj 
}
| Where-Object { ($_.REPOSITORY -eq $IMAGE_NAME) -and ($_.TAG -match "$($IMAGE_TAG)\.[\d]+") }

$CurrentImages | Format-Table 

# 递增
$IMAGE_TAG += ".$($CurrentImages.Length + 1)"

$IMAGE_NAME_AND_TAG = "$($IMAGE_NAME):$($IMAGE_TAG)"

$BUILD_DOCKER_COMMAND = "docker build -f ./Quickly.Certs.WebApi/Dockerfile -t $("$($IMAGE_NAME_AND_TAG)") ."
$UPDATE_LATEST_DOCKER_IMAGE_COMMAND = "docker tag $($IMAGE_NAME_AND_TAG) $($IMAGE_NAME_AND_TAG_LATEST)"

Write-Debug $BUILD_DOCKER_COMMAND
Invoke-Expression -Command $BUILD_DOCKER_COMMAND -ErrorAction Stop

Write-Debug $UPDATE_LATEST_DOCKER_IMAGE_COMMAND
Invoke-Expression -Command $UPDATE_LATEST_DOCKER_IMAGE_COMMAND -ErrorAction Stop